package com.lyl.goods.service.impl;

import com.lyl.goods.mapper.CartMapper;
import com.lyl.goods.pojo.ShoppingCart;
import com.lyl.goods.service.CartService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;
import java.util.Map;

/**
 * @Author: Liyunlong
 * @Date: 2024/03/01/19:10
 * @Description:
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;


    @Override
    public void add(Long productId) {
        // 从HttpSession中获取用户ID
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession(false);
        Integer userId = (Integer) session.getAttribute("userId");
        cartMapper.add(productId,userId);
    }



    @Override
    public void delete(Long cartId) {
        cartMapper.delete(cartId);
    }

    @Override
    public ShoppingCart selectByProductId(Long productId) {
        // 从HttpSession中获取用户ID
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession(false);
        Integer userId = (Integer) session.getAttribute("userId");

        return cartMapper.selectByProductId(productId,userId);
    }

    @Override
    public void update(Long productId, ShoppingCart shoppingCart) {
        int quantity = shoppingCart.getQuantity();
        cartMapper.update(productId,quantity);

    }

    @Override
    public ShoppingCart getByCartId(Long cartId) {
        return cartMapper.getByCartId(cartId);
    }

    @Override
    public void addQuantity(Long cartId, int quantity) {
        cartMapper.addQuantity(cartId,quantity);
    }
    /**
     * @Description: 这里的增加减少的的mapper层一样
     * @Author: Liyunlong
     * @Date: 2024/3/2
     */

    @Override
    public void JianQuantity(Long cartId, int quantity) {
        cartMapper.addQuantity(cartId,quantity);
    }

    @Override
    public List<ShoppingCart> cartList(Integer userId) {
        return cartMapper.cartList(userId);
    }

    @Override
    public List<Map<String, Object>> getCartItems(Integer userId) {
        return cartMapper.getCartItems(userId);
    }
}
